﻿using NCP.Infrastructure.Common.Domain;
using NCP.Recruiting.ApplicationServices.Interfaces;
using NCP.Recruiting.ApplicationServices.Messaging.Resumes;
using NCP.Recruiting.WebApp.Extensions;
using NCP.Recruiting.WebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NCP.Infrastructure.Common;
using NCP.Recruiting.ApplicationServices.ViewModels;
using NCP.Recruiting.Web.Framework.Controllers;
using NCP.Recruiting.ApplicationServices.Messaging.Candidates;
using NCP.Recruiting.ApplicationServices.Messaging.Bookmarks;

namespace NCP.Recruiting.WebApp.Controllers
{
    public class ResumeController : AuthorizedController
    {
        #region Const
        public readonly ICompanyAppService _CompanyAppService;
        public readonly IResumeAppService _ResumeAppService;
        public readonly ICandidateAppService _CandidateAppService;
        public readonly IBookmarkAppService _BookmarkAppService;
        private const int _pageSize = 15;

        private static List<SelectListItem> _FrequencyList;
        private static List<SelectListItem> FrequencyList
        {
            get
            {
                if (_FrequencyList == null)
                {
                    _FrequencyList = new List<SelectListItem>()
                    {
                        new SelectListItem(){ Text="每天",Value="1"},
                        new SelectListItem(){ Text="每三天", Value= "3"},
                        new SelectListItem(){ Text="每周", Value= "7"},
                        new SelectListItem(){ Text="每两周", Value= "14"},
                        new SelectListItem(){ Text="每月", Value= "30"},
                    };
                }
                return _FrequencyList;
            }
        }

        private static List<SelectListItem> _TalentsList;
        private static List<SelectListItem> TalentsList
        {
            get
            {
                if (_TalentsList == null)
                {
                    _TalentsList = new List<SelectListItem>()
                    {
                        new SelectListItem(){ Text="5份",Value="5"},
                        new SelectListItem(){ Text="10份", Value= "10"},
                        new SelectListItem(){ Text="15份", Value= "15"},
                        new SelectListItem(){ Text="30份", Value= "30"},
                    };
                }
                return _TalentsList;
            }
        }

        #endregion

        //
        // GET: /Resume/
        public ResumeController(ICompanyAppService companyAppService, IResumeAppService resumeAppService, ICandidateAppService candidateAppService, IBookmarkAppService bookmarkAppService)
            : base(companyAppService)
        {
            this._CompanyAppService = companyAppService;
            this._ResumeAppService = resumeAppService;
            this._CandidateAppService = candidateAppService;
            this._BookmarkAppService = bookmarkAppService;
        }

        #region List
        public ActionResult List(PagingFilteringModel command, Guid? searchId = null)
        {
            ResumeCondtionModel condtionModel = null;
            IPagedList<ResumeListItemModel> resumeList = null;

            if (command == null)
            {
                command = TempData["command"] as PagingFilteringModel;
                searchId = TempData["searchId"] != null ? (Nullable<Guid>)Guid.Parse(TempData["searchId"].ToString()) : null;
            }
            //初始化分页组件
            if (command.PageSize <= 0)
                command.PageSize = _pageSize;
            if (command.PageNumber <= 0)
                command.PageNumber = 1;

            if (searchId.HasValue)
            {
                //取得分页数据通过搜索器ID
                var response = _ResumeAppService.SearchBySearcherId(new SearchBySearcherIdRequest()
                {
                    PageIndex = command.PageIndex,
                    PageSize = command.PageSize,
                    CompanyId = this.CurrentUserId,
                    SearcherId = searchId.Value,
                });
                resumeList = response.ListItemModelList;
            }
            else if (TempData.ContainsKey("CondtionModel"))
            {
                condtionModel = TempData["CondtionModel"] as ResumeCondtionModel;
                //取得分页数据检索条件
                var response = _ResumeAppService.Search(new SearchRequest()
                {
                    PageIndex = command.PageIndex,
                    PageSize = command.PageSize,
                    ResumeCondtion = condtionModel,
                    CompanyId = this.CurrentUserId,
                });
                resumeList = response.ListItemModelList;
                TempData["CondtionModel"] = condtionModel;
            }

            var model = new ResumeListViewModel()
            {
                PagingFilteringContext = new PagingFilteringModel(),
            };
            model.PagingFilteringContext.LoadPagedList(resumeList);
            //转换成ViewModel
            model.ResumeList = resumeList;

            TempData["command"] = command;
            TempData["searchId"] = searchId;
            return View(model);
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("PreviewSelected")]
        public ActionResult PreviewSelected(String idList)
        {
            var list = (idList ?? String.Empty).Split(',').Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => Guid.Parse(x)).ToList();
            TempData["PreviewIdList"] = list;
            return RedirectToAction("Priview", new { id = list.First(), isShowSelected = true });
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("Bookmark")]
        public ActionResult Bookmark(Guid id)
        {
            var response = _BookmarkAppService.Create(new CreateBookmarkRequest()
            {
                CompanyId = this.CurrentUserId,
                ResumeId = id
            });
            return List(null);
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("BookmarkSelected")]
        public ActionResult BookmarkSelected(String idList)
        {
            var list = (idList ?? String.Empty).Split(',').Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => Guid.Parse(x)).ToList();
            list.ForEach(x => _BookmarkAppService.Create(new CreateBookmarkRequest()
            {
                CompanyId = this.CurrentUserId,
                ResumeId = x
            }));
            return List(null);
        }

        #endregion

        #region Priview
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">简历Id</param>
        /// <param name="isShowSelected">是否显示选中简历</param>
        /// <returns></returns>
        public ActionResult Priview(Guid id, bool isShowSelected = false)
        {
            //var response = _ResumeAppService.GetViewModelById(id);
            //response.IsResumePriview = true;
            //return View(response);

            var response = _ResumeAppService.GetResumeInfo(new GetResumeInfoRequest()
            {
                CompanyId = this.CurrentUserId,
                ResumeId = id
            });
            var resumeViewModel = response.ResumeViewModel;
            resumeViewModel.IsResumePriview = true;

            var model = new ResumePreviewModel()
            {
                ResumeViewModel = resumeViewModel,
            };

            if (isShowSelected && TempData.ContainsKey("PreviewIdList"))
            {
                var list = TempData["PreviewIdList"] as List<Guid>;
                var index = list.IndexOf(id);
                if (index > 0)
                {
                    model.PreviousId = list.ElementAt(index - 1);
                }
                if (index < list.Count() - 1)
                {
                    model.NextId = list.ElementAt(index + 1);
                }
                TempData["PreviewIdList"] = list;
            }
            return View(model);
        }

        [HttpPost]
        [ActionName("Priview")]
        [FormValueRequired("ShowContact")]
        public ActionResult ShowContact(Guid resumeId, bool isShowSelected = false)
        {
            var response = _CandidateAppService.SetShowContactFlag(new SetShowContactFlagRequest() { CompanyId = this.CurrentUserId, ResumeId = resumeId });
            if (response.Errors != null && response.Errors.Count > 0)
            {
                ViewBag.SetShowContactFlagError = response.Errors.FirstOrDefault();
            }
            return Priview(resumeId, isShowSelected);
        }

        #endregion

        #region Search
        #region AdvSearch
        public ActionResult AdvSearch()
        {
            var model = new ResumeCondtionModel();
            PrepareForResumeCondtionModel(model);
            return View(model);
        }

        [HttpPost]
        public ActionResult AdvSearch(ResumeCondtionModel model)
        {
            model.JobTypeList = (model.JobTypeListString ?? String.Empty).Split(',').Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => int.Parse(x));
            if (!TempData.ContainsKey("CondtionModel"))
            {
                TempData["CondtionModel"] = model;
            }
            else
            {
                TempData["CondtionModel"] = model;
            }
            //如果需要保存为搜索器
            if (model.IsSaveWhenSearch)
            {
                var request = new CreateSavedSearchRequest()
                {
                    CompanyId = this.CurrentUser.Id,
                    SearchName = model.SearchName,
                    ResumeCondtion = model
                };
                _ResumeAppService.CreateSavedSearch(request);
            }
            return RedirectToAction("List");
        }
        #endregion

        #region AddSearcher
        public ActionResult AddSearcher()
        {
            var model = new ResumeCondtionModel();
            PrepareForResumeCondtionModel(model);
            model.IsSaveWhenSearch = false;
            return View(model);
        }

        [HttpPost]
        [ActionName("AddSearcher")]
        [FormValueRequired("Save")]
        public ActionResult AddDoSave(ResumeCondtionModel model)
        {
            model.JobTypeList = (model.JobTypeListString ?? String.Empty).Split(',').Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => int.Parse(x));
            var request = new CreateSavedSearchRequest()
            {
                CompanyId = this.CurrentUser.Id,
                SearchName = model.SearchName,
                ResumeCondtion = model
            };
            _ResumeAppService.CreateSavedSearch(request);
            return RedirectToAction("SearcherList");
        }

        [HttpPost]
        [ActionName("AddSearcher")]
        [FormValueRequired("Search")]
        public ActionResult AddDoSearch(ResumeCondtionModel model)
        {
            return AdvSearch(model);
        }
        #endregion

        #region EditSearcher
        public ActionResult EditSearcher(Guid id)
        {
            var response = _ResumeAppService.GetConditionBySavedSearchId(new GetConditionBySavedSearchIdRequest() { Id = id });
            var model = response.ResumeCondtion.CopyItem<ResumeCondtionViewModel, ResumeCondtionModel>();
            PrepareForResumeCondtionModel(model);
            model.IsSaveWhenSearch = false;
            model.SearchName = response.SearchName;
            model.Id = id;
            return View(model);
        }

        [HttpPost]
        [ActionName("EditSearcher")]
        [FormValueRequired("Save")]
        public ActionResult EditDoSave(ResumeCondtionModel model)
        {
            model.JobTypeList = (model.JobTypeListString ?? String.Empty).Split(',').Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => int.Parse(x));
            var request = new UpdateSavedSearchRequest()
            {
                Id = model.Id,
                SearchName = model.SearchName,
                ResumeCondtion = model
            };
            _ResumeAppService.UpdateSavedSearch(request);
            return RedirectToAction("SearcherList");
        }

        [HttpPost]
        [ActionName("EditSearcher")]
        [FormValueRequired("Search")]
        public ActionResult EditSearcher(ResumeCondtionModel model)
        {
            return AdvSearch(model);
        }
        #endregion

        #region SearcherList
        public ActionResult SearcherList(PagingFilteringModel command)
        {
            if (command == null)
            {
                command = TempData["command"] as PagingFilteringModel;
            }
            //初始化分页组件
            if (command.PageSize <= 0)
                command.PageSize = _pageSize;
            if (command.PageNumber <= 0)
                command.PageNumber = 1;

            //取得分页数据
            var response = _ResumeAppService.GetSavedSearchList(new GetSavedSearchListRequest()
            {
                PageIndex = command.PageIndex,
                PageSize = command.PageSize,
                CompanyId = this.CurrentUserId
            });
            var model = new SavedSearchListViewModel()
            {
                PagingFilteringContext = new PagingFilteringModel(),
            };
            model.PagingFilteringContext.LoadPagedList(response.ListItemModelList);
            //转换成ViewModel
            model.SavedSearchList = response.ListItemModelList;
            foreach (var item in model.SavedSearchList)
            {
                var frequency = FrequencyList.FirstOrDefault(x => x.Value.Equals(item.Frequency));
                item.Frequency = frequency == null ? String.Empty : frequency.Text;

                var talents = TalentsList.FirstOrDefault(x => x.Value.Equals(item.Talents));
                item.Talents = frequency == null ? String.Empty : talents.Text;
            }
            model.ResumeSubscribe = new ResumeSubscribeFormModel();
            model.ResumeSubscribe.FrequencyList = FrequencyList;
            model.ResumeSubscribe.TalentsList = TalentsList;

            TempData["command"] = command;
            return View(model);
        }

        /// <summary>
        /// 删除所选
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("SearcherList")]
        [FormValueRequired("DeleteSelected")]
        public ActionResult DeleteSelectedSearcher(String idList)
        {
            var list = (idList ?? String.Empty).Split(',').Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => Guid.Parse(x));
            foreach (var id in list)
            {
                _ResumeAppService.DeleteSavedSearch(new DeleteSavedSearchRequest() { Id = id });
            }
            return SearcherList(null);
        }

        /// <summary>
        /// 退订
        /// </summary>
        /// <param name="unsubscribeId"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("SearcherList")]
        [FormValueRequired("Unsubscribe")]
        public ActionResult Unsubscribe(Guid unsubscribeId)
        {
            _ResumeAppService.Unsubscribe(new UnsubscribeRequest() { Id = unsubscribeId });
            return SearcherList(null);
        }

        /// <summary>
        /// 订阅
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("SearcherList")]
        [FormValueRequired("Subscribe")]
        public ActionResult Subscribe(SavedSearchListViewModel model)
        {
            _ResumeAppService.Subscribe(new SubscribeRequest() { ResumeSubscribe = model.ResumeSubscribe });
            return SearcherList(null);
        }
        #endregion

        #endregion

        #region Other
        /// <summary>
        /// 为显示模型附加上相关数据
        /// </summary>
        /// <param name="model"></param>
        public void PrepareForResumeCondtionModel(ResumeCondtionModel model)
        {
            model.AgeList = new List<SelectListItem>();
            for (var i = 18; i < 60; i++)
            {
                model.AgeList.Add(new SelectListItem() { Text = i.ToString(), Value = i.ToString() });
            }

            model.DayRangeList = new List<SelectListItem>()
            {
                new SelectListItem(){ Text="7天内",Value="7"},
                new SelectListItem(){ Text="15天内",Value="15"},
                new SelectListItem(){ Text="30天内",Value="30"},
                new SelectListItem(){ Text="90天内",Value="90"},
                new SelectListItem(){ Text="360天内",Value="360"},
            };

            model.YearsOfExperienceList = Common.GenerateDropDownListSource(LovType.YearsOfExperience);
            model.DesiredIndustryList = Common.GenerateDropDownListSource(LovType.Industry);
            model.DesiredJobTypeList = Common.GenerateDropDownListSource(LovType.JobType);
            model.DesiredSalaryList = Common.GenerateDropDownListSource(LovType.SalaryRange);
            model.EducationLevelList = Common.GenerateDropDownListSource(LovType.EducationLevel);
            model.GenderList = LovHandler.GetListByParentId(LovHandler.GetLovId(LovType.Gender));
            model.MajorList = Common.GenerateDropDownListSource(LovType.Major);
        }
        #endregion
    }
}
